<template>
    <div class="role-manage-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <el-icon class="header-icon">
                        <Avatar />
                    </el-icon>
                    <h2 class="page-title">管理角色</h2>
                </div>
                <div class="header-right">
                    <el-button type="primary" @click="refreshData">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        刷新
                    </el-button>
                    <el-button type="success" @click="goToAddRole">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加角色
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-section">
            <el-card class="search-card">
                <el-form :model="searchForm" inline>
                    <el-form-item label="角色名称：">
                        <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable style="width: 300px"
                            @keyup.enter="handleSearch" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">
                            <el-icon>
                                <Search />
                            </el-icon>
                            查询
                        </el-button>
                        <el-button @click="handleReset">
                            <el-icon>
                                <RefreshLeft />
                            </el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <!-- 表格区域 -->
        <div class="table-section">
            <el-card class="table-card">
                <el-table :data="roleList" v-loading="loading" stripe style="width: 100%"
                    :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="roleId" label="角色编号" align="center" width="100">
                        <template #default="scope">
                            <el-tag type="primary" effect="light">
                                {{ scope.row.roleId }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="roleName" label="角色名称" align="center" min-width="120">
                        <template #default="scope">
                            <el-text type="primary" class="role-name">
                                {{ scope.row.roleName }}
                            </el-text>
                        </template>
                    </el-table-column>
                    <el-table-column prop="permissions" label="权限" align="center" min-width="200">
                        <template #default="scope">
                            <div class="permissions-list">
                                <div v-if="scope.row.permissions && Array.isArray(scope.row.permissions)">
                                    <el-tag v-for="(permission, index) in scope.row.permissions" :key="index"
                                        type="success" size="small" class="permission-tag">
                                        {{ permission }}
                                    </el-tag>
                                </div>
                                <div v-else-if="scope.row.permissonName">
                                    <el-tag type="success" size="small" class="permission-tag">
                                        {{ scope.row.permissonName }}
                                    </el-tag>
                                </div>
                                <div v-else>
                                    <el-tag type="info" size="small">无权限</el-tag>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="isEnabled" label="是否启用" align="center" width="100">
                        <template #default="scope">
                            <el-tag :type="scope.row.state ? 'primary' : 'danger'" effect="light">
                                {{ scope.row.state ? '启用' : '禁用' }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop="createTime" label="创建时间" align="center" width="120">
                        <template #default="scope">
                            <el-text type="info" class="time-text">
                                {{ scope.row.createTime }}
                            </el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="250" fixed="right">
                        <template #default="scope">
                            <div class="action-buttons">
                                <div class="button-row">
                                    <el-button type="primary" size="small" @click="updateRole2(scope.row)"
                                        class="action-btn edit-btn">
                                        <el-icon>
                                            <Edit />
                                        </el-icon>
                                        修改
                                    </el-button>
                                    <el-button type="danger" size="small" @click="handleDelete(scope.row)"
                                        class="action-btn delete-btn">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                        删除
                                    </el-button>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
                <el-dialog v-model="dialogFormVisible" title="修改角色" width="500">
                    <el-form :model="roleForm" label-width="120px">
                        <el-form-item label="角色名称">
                            <el-input v-model="roleForm.roleName" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="权限分配">
                            <el-checkbox-group v-model="roleForm.permissonIds">
                                <el-checkbox v-for="item in RoleData" :key="item.permissonId" :label="item.permissonId">
                                    {{ item.permissonName }}
                                </el-checkbox>
                            </el-checkbox-group>
                            <div style="margin-top: 10px; font-size: 12px; color: #666;">
                                当前选中的权限ID: {{ roleForm.permissonIds }}
                            </div>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="update">确认修改</el-button>
                        </div>
                    </template>
                </el-dialog>
            </el-card>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const route = useRoute()
const router = useRouter()
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Avatar,
    Refresh,
    Plus,
    Search,
    RefreshLeft,
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { read } from '@/Until/axiosHepler'
interface RoleForm {
    roleId: number,
    roleName: string,
    permissonIds: number[]
}

const updateRole2 = (row: any) => {
    console.log('选中的行数据:', row) // 调试信息
    console.log('权限数据:', RoleData.value) // 调试信息
    console.log('权限数据结构:', RoleData.value.map(item => ({
        id: item.permissonId,
        name: item.permissonName,
        value: item.permissonValue
    }))) // 详细显示权限数据结构

    // 回显数据到表单
    roleForm.roleId = row.roleId
    roleForm.roleName = row.roleName

    // 清空之前的权限选择
    roleForm.permissonIds = []

    // 处理权限回显 - 支持多种数据结构
    let permissionsToShow: string[] = []

    if (row.permissions && Array.isArray(row.permissions)) {
        // 如果数据有permissions数组，确保是字符串数组
        permissionsToShow = row.permissions.filter((p: any) => typeof p === 'string')
    } else if (row.permissonName) {
        // 如果数据有permissonName字段
        if (Array.isArray(row.permissonName)) {
            permissionsToShow = row.permissonName.filter((p: any) => typeof p === 'string')
        } else if (typeof row.permissonName === 'string') {
            permissionsToShow = [row.permissonName]
        }
    } else if (row.permissionName) {
        // 如果数据有permissionName字段
        if (Array.isArray(row.permissionName)) {
            permissionsToShow = row.permissionName.filter((p: any) => typeof p === 'string')
        } else if (typeof row.permissionName === 'string') {
            permissionsToShow = [row.permissionName]
        }
    }

    console.log('要回显的权限:', permissionsToShow) // 调试信息
    console.log('权限数组长度:', permissionsToShow.length) // 调试信息

    // 将权限名称转换为权限ID
    if (permissionsToShow.length > 0) {
        roleForm.permissonIds = permissionsToShow.map((p: string) => {
            console.log(`正在查找权限: "${p}"`) // 调试信息

            // 尝试多种匹配方式
            let permission = RoleData.value.find(item => item.permissonName === p)

            if (!permission) {
                // 尝试匹配 permissonValue
                permission = RoleData.value.find(item => item.permissonValue === p)
            }

            if (!permission) {
                // 尝试匹配其他可能的字段
                permission = RoleData.value.find(item =>
                    item.name === p ||
                    item.permissionName === p ||
                    item.permissionValue === p
                )
            }

            console.log(`查找权限 "${p}" 结果:`, permission) // 调试信息
            return permission ? permission.permissonId : null
        }).filter((id: any) => id !== null)
    }

    console.log('回显的权限ID:', roleForm.permissonIds) // 调试信息
    console.log('表单数据:', roleForm) // 调试信息

    // 如果权限ID为空，尝试直接使用权限名称匹配
    if (roleForm.permissonIds.length === 0 && permissionsToShow.length > 0) {
        console.log('尝试直接匹配权限名称...')
        roleForm.permissonIds = RoleData.value
            .filter(item =>
                permissionsToShow.includes(item.permissonName) ||
                permissionsToShow.includes(item.permissonValue) ||
                permissionsToShow.includes(item.name) ||
                permissionsToShow.includes(item.permissionName) ||
                permissionsToShow.includes(item.permissionValue)
            )
            .map(item => item.permissonId)
        console.log('直接匹配后的权限ID:', roleForm.permissonIds)
    }

    // 使用nextTick确保DOM更新后再打开对话框
    nextTick(() => {
        dialogFormVisible.value = true
    })
}
// 初始化表单数据
const roleForm = reactive<RoleForm>({
    roleId: 0,
    roleName: "",
    permissonIds: []
})
onMounted(() => {
    roleList1(); // 获取权限列表
    fetchData(); // 获取角色列表
})
const RoleData = ref<any[]>([])
const roleList1 = () => {
    axios.get("http://localhost:5134/api/User/PermissonList").then((res) => {
        console.log('权限列表API响应:', res.data) // 调试信息
        RoleData.value = res.data.data || []
        console.log('权限数据:', RoleData.value) // 调试信息

        // 详细显示每个权限的字段
        if (RoleData.value.length > 0) {
            console.log('第一个权限的完整结构:', RoleData.value[0])
            console.log('所有权限的字段名:', Object.keys(RoleData.value[0]))
            console.log('权限数据示例:', RoleData.value.map(item => ({
                id: item.permissonId,
                name: item.permissonName,
                value: item.permissonValue
            })))
        }
    }).catch((error) => {
        console.error('获取权限列表失败:', error)
        ElMessage.error('获取权限列表失败')
    })
}
const update = () => {
    // 构建更新数据
    const updateData = {
        roleId: roleForm.roleId,
        roleName: roleForm.roleName,
        permissonIds: roleForm.permissonIds
    }

    axios.post("http://localhost:5219/api/Manger/UpdateRole", updateData).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success('修改成功')
            dialogFormVisible.value = false
            // 刷新数据
            fetchData()
        } else {
            ElMessage.error('修改失败')
        }
    }).catch((error) => {
        console.error('修改角色失败:', error)
        ElMessage.error('修改失败')
    })
}
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'



// 角色数据类型定义
interface RoleData {

    roleName: string
    permissions: string[]
    isEnabled: boolean
    sequence: number
    createTime: string
}

const updateRole = (row: any) => {
    router.push({
        path: '/MainView/EditRoleView',
        query: { roleId: row.roleId }
    })
}
// 响应式数据
const roleList = ref<RoleData[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
    roleName: ''
})

// 默认角色数据（根据图片内容）
const defaultRoleData = [
    {
        roleId: 1,
        roleName: 'admin',
        permissions: ['试题管理', '考试', '查看成绩', '成绩分析'],
        isEnabled: true,
        sequence: 1,
        createTime: '2018-06-20'
    },
    {
        roleId: 2,
        roleName: '教师',
        permissions: ['试题管理', '成绩分析'],
        isEnabled: true,
        sequence: 2,
        createTime: '2018-06-20'
    },
    {
        roleId: 3,
        roleName: '学生',
        permissions: ['考试', '查看成绩'],
        isEnabled: true,
        sequence: 3,
        createTime: '2018-06-20'
    },
    {
        roleId: 4,
        roleName: 'boss',
        permissions: ['试题管理', '考试', '查看成绩', '成绩分析'],
        isEnabled: true,
        sequence: 4,
        createTime: '2018-06-20'
    }
]

// 获取角色列表数据
const fetchData = async () => {
    loading.value = true
    try {
        // 先尝试从API获取数据
        const response = await read.get("/api/User/RoleList", {
            params: {
                roleName: searchForm.roleName,

            }
        })

        if (response.data.code === 200) {
            roleList.value = response.data.data || []
            // total.value = response.data.total || roleList.value.length
        } else {
            // API失败时使用默认数据
            console.log('API调用失败，使用默认数据')
            useDefaultData()
        }
    } catch (error) {
        // API调用失败时使用默认数据
        console.log('API调用失败，使用默认数据:', error)
        useDefaultData()
    } finally {
        loading.value = false
    }
}

// 使用默认数据
const useDefaultData = () => {
    let filteredData = defaultRoleData

    // 如果有搜索条件，进行过滤
    if (searchForm.roleName) {
        filteredData = defaultRoleData.filter(role =>
            role.roleName.toLowerCase().includes(searchForm.roleName.toLowerCase())
        )
    }

    // 分页处理
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    roleList.value = filteredData.slice(startIndex, endIndex)
    total.value = filteredData.length
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    // 直接使用默认数据进行搜索，避免API调用
    useDefaultData()
}

// 重置搜索
const handleReset = () => {
    searchForm.roleName = ''
    currentPage.value = 1
    // 直接使用默认数据，避免API调用
    useDefaultData()
}

// 刷新数据
const refreshData = () => {
    fetchData()
}

// 跳转到添加角色页面
const goToAddRole = () => {
    router.push('/MainView/AddRoleView')
}

// 编辑角色
const handleEdit = (row: any) => {
    router.push({
        path: '/MainView/EditRole',
        query: { roleId: row.roleId }
    })
}

// 删除角色
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除角色 "${row.roleName}" 吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        // 这里调用删除API
        await axios.delete(`http://localhost:5134/api/Role/DeleteRole/${row.roleId}`)
        ElMessage.success('删除成功')
        fetchData()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
            console.error('Error deleting role:', error)
        }
    }
}

// 分页处理
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    // 直接使用默认数据进行分页，避免API调用
    useDefaultData()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    // 直接使用默认数据进行分页，避免API调用
    useDefaultData()
}

// 组件挂载时获取数据
onMounted(() => {
    // 直接使用默认数据，避免API调用
    useDefaultData()
    fetchData();
})
</script>

<style scoped>
.role-manage-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 20px 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.header-icon {
    font-size: 24px;
    color: #409eff;
}

.page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    background: linear-gradient(135deg, #409eff, #67c23a);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.header-right {
    display: flex;
    gap: 12px;
}

/* 搜索区域样式 */
.search-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border: none;
}

.search-card :deep(.el-card__body) {
    padding: 20px 24px;
}

/* 表格区域样式 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border: none;
}

.table-card :deep(.el-card__body) {
    padding: 0;
}

/* 表格样式 */
:deep(.el-table) {
    border-radius: 12px;
    overflow: hidden;
}

:deep(.el-table__header) {
    background: #f8f9fa;
}

:deep(.el-table th) {
    background: #f8f9fa !important;
    color: #606266;
    font-weight: 600;
    border-bottom: 2px solid #e4e7ed;
}

:deep(.el-table td) {
    border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
    background: #f0f9ff !important;
}

/* 角色名称样式 */
.role-name {
    font-weight: 600;
    font-size: 14px;
}

/* 权限标签样式 */
.permissions-list {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    justify-content: center;
    align-items: center;
}

.permission-tag {
    margin: 2px;
    border-radius: 8px;
    font-size: 12px;
}

/* 时间文本样式 */
.time-text {
    font-size: 12px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 分页样式 */
.pagination-container {
    padding: 20px 24px;
    display: flex;
    justify-content: center;
    background: #fafbfc;
    border-top: 1px solid #e4e7ed;
}

:deep(.el-pagination) {
    justify-content: center;
}

:deep(.el-pagination .el-pager li) {
    border-radius: 6px;
    margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
    background: #409eff;
    color: white;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
    border-radius: 6px;
}

/* 操作列按钮样式 */
.action-buttons {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}

.button-row {
    display: flex;
    gap: 8px;
    align-items: center;
}

.action-btn {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
    border: none;
    min-width: 70px;
    height: 32px;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.edit-btn {
    background: linear-gradient(135deg, #409eff, #67c23a);
    color: white;
}

.edit-btn:hover {
    background: linear-gradient(135deg, #337ecc, #529b2e);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.delete-btn {
    background: linear-gradient(135deg, #f56c6c, #f78989);
    color: white;
}

.delete-btn:hover {
    background: linear-gradient(135deg, #f23030, #f56c6c);
    box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.action-btn .el-icon {
    font-size: 14px;
}

/* 按钮样式优化 */
:deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

:deep(.el-button:hover) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-button--primary) {
    background: linear-gradient(135deg, #409eff, #67c23a);
    border: none;
}

:deep(.el-button--success) {
    background: linear-gradient(135deg, #67c23a, #85ce61);
    border: none;
}

:deep(.el-button--danger) {
    background: linear-gradient(135deg, #f56c6c, #f78989);
    border: none;
}

/* 标签样式 */
:deep(.el-tag) {
    border-radius: 6px;
    font-weight: 500;
}

:deep(.el-tag--primary) {
    background: linear-gradient(135deg, #409eff, #67c23a);
    color: white;
    border: none;
}

:deep(.el-tag--success) {
    background: linear-gradient(135deg, #67c23a, #85ce61);
    color: white;
    border: none;
}

:deep(.el-tag--danger) {
    background: linear-gradient(135deg, #f56c6c, #f78989);
    color: white;
    border: none;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff;
}

:deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 卡片样式 */
:deep(.el-card) {
    border: none;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

:deep(.el-card:hover) {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .role-manage-container {
        padding: 10px;
    }

    .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
    }

    .header-right {
        justify-content: center;
    }

    .search-card :deep(.el-form) {
        flex-direction: column;
        align-items: stretch;
    }

    .search-card :deep(.el-form-item) {
        margin-right: 0;
        margin-bottom: 16px;
    }

    .search-card :deep(.el-input) {
        width: 100% !important;
    }

    .action-buttons {
        flex-direction: column;
        gap: 6px;
    }

    .button-row {
        flex-direction: column;
        gap: 6px;
    }

    .action-btn {
        min-width: 60px;
        height: 28px;
        font-size: 11px;
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 20px;
    }

    .header-icon {
        font-size: 20px;
    }

    :deep(.el-table) {
        font-size: 12px;
    }

    .action-btn {
        padding: 6px 10px;
        font-size: 10px;
        min-width: 50px;
        height: 26px;
    }
}
</style>
